import RestFetch from '@/utils/request/FhFetch'
import { ElLoadingService, ElMessage } from 'element-plus'
import type { ILoadingInstance } from 'element-plus'
import type { RequestOptions } from '@/utils/request/RestFetch'

const restFetch = new RestFetch({
  baseURL: import.meta.env.VITE_BASE_API,
})

interface InitOptions{
  msg?: string;
  loading?: boolean;
}

export interface JsonrpcBaseResponse<T> {
  id: string
  jsonrpc: string
  error?: {
    code: number,
    message: string,
  }
  result: T
}

async function request<T> (options: Partial<RequestOptions>, init?: InitOptions):Promise<T> {
  const loading = !!init?.loading
  let loadingService:ILoadingInstance|null = null
  if (loading) {
    loadingService = ElLoadingService({})
  }
  const defaultOptions = {
    id: '1',
    jsonrpc: '2.0',
  }

  if (options.method === 'GET') {
    options.params = {
      ...defaultOptions,
      ...options.params,
    }
  } else {
    options.data = {
      ...defaultOptions,
      ...options.data,
    }
  }
  const res = await restFetch.request<JsonrpcBaseResponse<T>>({
    method: 'POST',
    url: '',
    ...options,
  })

  if (res.error) {
    ElMessage({
      type: 'error',
      message: res.error.message,
    })
  }

  if (res.result && init?.msg) {
    ElMessage({
      type: 'success',
      message: init.msg,
    })
  }

  loadingService?.close()
  return res.result
}

export default request